package com.example.springboot2.oa.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot2.base.web.BaseController;
import com.example.springboot2.oa.entity.TDepartment;
import com.example.springboot2.oa.entity.TUser;
import com.example.springboot2.oa.jstree.TreeNode;
import com.example.springboot2.oa.service.ITDepartmentService;
import com.example.springboot2.oa.service.ITUserService;
import com.example.springboot2.tools.MakeResponse;
import com.example.springboot2.tools.ResponseMessage;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  用户控制层
 * </p>
 *
 * @author llfy
 * @since 2018-11-23
 */
@CrossOrigin
@RestController
@RequestMapping("/oa/t-department")
public class TDepartmentController extends BaseController {

    /**
     *注入userService
     */
    @Autowired
    private ITDepartmentService departmentService;
    @Autowired
    private ITUserService userService;

     /**
     * 用户列表
     * @return
     */
    @ApiOperation(value = "机构树")
    @GetMapping("listTree")
    public ResponseMessage listTree(String token){
        //验证是否登陆
        QueryWrapper<TUser> userToken = new QueryWrapper<>();
        userToken.eq("token",token);
        TUser tUser = userService.getOne(userToken);
        if (tUser == null){
            return MakeResponse.success("401","无权限访问");
        }
        //List<TStudent> data = departmentService.listService.listStudent(studentName);
        List<TreeNode> depts = this.getTree();
        return MakeResponse.success("200","机构树", depts);
    }

    private List<TreeNode> getTree() {
        List<TreeNode> list=new ArrayList<TreeNode>();
        List<TDepartment> roots = departmentService.getDepartmentsByByParentID(0);
        for(TDepartment dept:roots){
            TreeNode node=new TreeNode();
            //node.setAttr(new TreeAttr(menu.getM_id()+"", menu.getParent_id()+"", menu.getM_name(), menu.getM_url(), menu.getM_order()+""));
            //node.setData(new TreeData(menu.getM_name()));//(menu.getM_url() == null ? "" : "(URL:" + menu.getM_url() + ")")
            //node.setState(TreeNode.NODE_OPEN);
            node.setId(String.valueOf(dept.getDeptId()));
            node.setText(dept.getDeptName());
            node.setParentId(String.valueOf(dept.getParentId()));
            node.setDesc(dept.getDeptDesc());
            list.add(node);
            getChildren(dept,node);
        }

        return list;
    }

    private void getChildren(TDepartment root,TreeNode node){
        root.setSubDepartmentList(departmentService.getDepartmentsByByParentID(root.getDeptId()));
        if(root.getSubDepartmentList()!=null && root.getSubDepartmentList().size()>0){
            node.setChildren(new ArrayList<TreeNode>());
            for(TDepartment department : root.getSubDepartmentList()){
                TreeNode mnode=new TreeNode();
                mnode.setId(String.valueOf(department.getDeptId()));
                mnode.setText(department.getDeptName());
                mnode.setParentId(String.valueOf(department.getParentId()));
                mnode.setDesc(department.getDeptDesc());
                node.getChildren().add(mnode);
                getChildren(department, mnode);
            }
        }else{
            //node.setState("{'opened' : false }");
        }
    }

    @ApiOperation(value = "新增机构")
    @PostMapping("addDept")
    public ResponseMessage addDept(@RequestBody TDepartment department,HttpServletRequest request){
        //验证名称是否重复
//        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
//        wrapper.eq("user_name",user.getUserName());
//        TUser userFlag = userService.getOne(wrapper);
//        if (userFlag != null){
//            return MakeResponse.success("500","用户名已存在");
//        }
        //新增操作
        //user.setId(String.valueOf(UUID.randomUUID()));
        //student.setCreateTime(new Date());
        //user.setUserPwd("000000");
        //user.setUserState(0);
        Boolean flag = departmentService.save(department);
        if (flag){
            return MakeResponse.success("200","新增成功");
        }
        return MakeResponse.success("500","新增失败");
    }

    @ApiOperation(value = "修改部门")
    @PostMapping("updateDept")
    public ResponseMessage updateDept(@RequestBody TDepartment department,HttpServletRequest request){
        //验证是否登陆
        QueryWrapper<TUser> userToken = new QueryWrapper<>();
        userToken.eq("token",request.getHeader("token"));
        TUser tUser = userService.getOne(userToken);
        if (tUser == null){
            return MakeResponse.success("401","无权限访问");
        }
        Boolean flag = departmentService.updateById(department);
        if (flag){
            return MakeResponse.success("200","更新成功");
        }
        return MakeResponse.success("500","更新失败");
    }

    /**
     * 删除学生
     * @param deptId
     * @return
     */
    @ApiOperation(value = "删除部门")
    @PostMapping("deleteDept")
    public ResponseMessage deleteDept(int deptId,HttpServletRequest request){
        //验证是否登陆
        QueryWrapper<TUser> userToken = new QueryWrapper<>();
        userToken.eq("token",request.getHeader("token"));
        TUser tUser = userService.getOne(userToken);
        if (tUser == null){
            return MakeResponse.success("401","无权限访问");
        }
        //int deptId = dept.getDeptId();
        List<TDepartment> deptList = departmentService.getDepartmentsByByParentID(deptId);
        if(deptList!=null && deptList.size()>0){
            return MakeResponse.success("500","该部门有下级部门，不能删除，请末级部门开始删除！");
        }
        //删除操作
        Boolean flag = departmentService.removeById(deptId);
        if (flag){
            return MakeResponse.success("200","删除成功");
        }
        return MakeResponse.success("500","删除失败");
    }
}
